package com.lengyu.iottransfer.gateway.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lengyu.iottransfer.gateway.common.CommonUtils;
import com.lengyu.iottransfer.gateway.common.HttpRequestUtil;
import com.lengyu.iottransfer.gateway.dto.MqttDeviceCurrentDto;
import com.lengyu.iottransfer.gateway.redis.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class CarBeiDouGPSService {
    private final static Logger logger = LoggerFactory.getLogger(CarBeiDouGPSService.class);
    private static final String id="NzAxLjY0MjUuNzI0";
//    private static final String password="888888";
    private static final String BASE_URL="http://39.103.174.164:8083/video/webapi/";


    @Autowired
    RedisUtils redisUtils;

    /**
     * Cacheable：触发缓存填充的操作，检查缓存是否存在，存在则取缓存数据,直接返回，不存在则查数据库写入缓存
     * value：缓存的名称，每个缓存名称下可以有多个key
     * key：缓存的key
     * condition：设置缓存的判断条件，当返回值不为 null 时才存缓存
     * unless：与condition相反，满足条件则不缓存
     * @param id
     * @return
     */
    @Cacheable(cacheManager = "cacheManager2" ,value = "getGpsToken", key = "#id", unless = "#result == null")
    public String getToken(String id){
        JSONObject param=new JSONObject();
        param.put("id",id);
        param.put("secret","d3b293e833bb86ee32f9792928f98f2e");
        String result = HttpRequestUtil.doPost(BASE_URL+"user/login","",param.toJSONString());
        JSONObject resultObj = JSONObject.parseObject(result);
        if(resultObj.containsKey("code")&& resultObj.getInteger("code") == 200){
            String token=resultObj.getJSONObject("data").getString("token");
            return token;
        }
        else{
            logger.error(result);
            return null;
        }
    }


    /**
     * 根据设备编码获取位置
     * @param plates 设备编码 ，多个编码用，隔开
     * @return
     */
    public JSONObject getGPSLocationByPlate(String plates){
        Long lastTime =  redisUtils.getLong("_carGPS_" + plates);
        String token = getToken(id);
        JSONObject param=new JSONObject();

        param.put("plates",plates);
        if(lastTime != null){
            param.put("time",lastTime);
        }

        JSONObject headerJson = new JSONObject();
        headerJson.put("Authorization",token);
        String result = HttpRequestUtil.doPostHeaderbody(BASE_URL+"location/get-location-use-plates",headerJson,param);
        logger.info("GPS定位信息查询：" + result);
        JSONObject resultObj = JSONObject.parseObject(result);
        if(resultObj.containsKey("code")&& resultObj.getInteger("code") == 200){
            JSONObject currentData = resultObj.getJSONObject("data");
            if(currentData!= null && currentData.keySet() != null  && currentData.getJSONArray("data").size() > 0 ){
               redisUtils.setLong("_carGPS_" + plates,currentData.getLong("time"));
                return currentData;
            }
            else{
                return null;
            }
        }
        else{
            logger.error(result);
            return null;
        }
    }

    public List<MqttDeviceCurrentDto> convertToMqttDeviceCurrentDto(JSONArray currentJsonArray){
        List<MqttDeviceCurrentDto> deviceCurrentDtoList = new ArrayList<>();
        if(!currentJsonArray.isEmpty() && currentJsonArray.size() > 0){
            for(int i=0;i<currentJsonArray.size();i++){
                try{

                    JSONObject currentJson = currentJsonArray.getJSONObject(i);
                    MqttDeviceCurrentDto mqttDeviceCurrentDto = new MqttDeviceCurrentDto();
                    mqttDeviceCurrentDto.setDeviceCode(currentJson.getString("devicecoding"));
                    mqttDeviceCurrentDto.setTime(CommonUtils.YMDHMSToDate(currentJson.getString("gpstime")).getTime());
                    mqttDeviceCurrentDto.setMethod("");

                    JSONObject param = new JSONObject();

                    param.put("lng",currentJson.getBigDecimal("lng"));
                    param.put("lat",currentJson.getBigDecimal("lat"));
                    param.put("glng",currentJson.getBigDecimal("glng"));
                    param.put("glat",currentJson.getBigDecimal("glat"));
                    param.put("blng",currentJson.getBigDecimal("blng"));
                    param.put("blat",currentJson.getBigDecimal("blat"));
                    param.put("location_mode_str",currentJson.getString("location_mode_str"));
                    param.put("av_str",currentJson.getString("av_str"));
                    param.put("satellite",currentJson.getInteger("satellite"));
                    param.put("gsm",currentJson.getInteger("gsm"));
                    param.put("electricity",currentJson.getBigDecimal("electricity"));
                    param.put("duelectricity",currentJson.getBigDecimal("duelectricity"));
                    param.put("address",currentJson.getString("adree"));
                    param.put("online",currentJson.getBoolean("online"));
                    mqttDeviceCurrentDto.setParams(param);

                    deviceCurrentDtoList.add(mqttDeviceCurrentDto);
                }
                catch (Exception ex){
                    logger.error("转换失败",ex);
                    continue;
                }

            }

        }
        return deviceCurrentDtoList;

    }
}
